/**
 * 右侧图层的列表
 * @param map
 * @param id
 */
function loadLayerTreeControl(map, id) {
    let tree = document.getElementById(id)
    visibleLayers = viewLayers.map((it) => it.getVisible())
    visibleLayers[0] = true
    viewLayers[0].setVisible(true)
    layerNames = resultLayers.map((it) => it.Name)
    viewLayers.forEach((it, index) => {
        let eleLi = document.createElement("li")
        tree.appendChild(eleLi)
        let eleInput = document.createElement("input")
        eleInput.checked = visibleLayers[index]
        eleInput.type = "checkbox"
        eleLi.appendChild(eleInput)
        let eleLabel = document.createElement("label")
        eleLabel.className = "layer"
        eleLabel.innerHTML = getIcon(resultLayers[index]) + " \t" + layerNames[index]
        eleLi.appendChild(eleLabel)
        addChangeEvent(eleInput, it)
    })
}

/**
 * layui 弹窗上选定的图层序号
 */
var _layuiLayerNumber = 0

function getLayerNumberFromLayUI() {
    return _layuiLayerNumber
}

var curLayUILayer

/**
 *
 * @param element checkbox元素
 * @param {ol.layer.Layer} layer 图层对象
 */
function addChangeEvent(element, layer) {
    element.onclick = () => layer.setVisible(element.checked)
}

function bindEditMenu() {
    $("#editItem").on('click', () => {
        editMenuModify.run()
    })
}
function getQueryString(name) {
    var reg =new RegExp('(^|&)'+ name +'=([^&]*)(&|$)','i');
    var r = window.location.search.substr(1).match(reg);
    if(r !=null) {
        return unescape(r[2]);
    }
    return null;
}
function getUsername() {
    console.log(getQueryString("name"))
    $("#loginUsername")[0].innerText = getQueryString("name")
}

function bindUIListeners() {
    layui.use(["element", "layer", "form"], () => {
        let layer = layui.layer
        let form = layui.form
        bindUseLayUILayerSearch(layer, form)
        bindMapNavItemMenu()
        bindMeasuresMenu()
        bindEditMenu()
        bindUserMenu()
    })
}

/**
 * 生成options内容
 * @param opts
 */
function generateLayuiLayerFormOptions(opts) {
    layerNames.forEach((it, index) => {
        let deptOption = $(`<option value='${index}'>${it}</option>`)
        opts.append(deptOption)
    })
}

/**
 * 【搜索】菜单
 * @param layer
 * @param form
 */
const bindSearchMenu = (layer, form) => {
    /**
     * 普通查询
     */
    function bindCommonSearch() {
        $("#search").on("click", () => {
            removeOthers()
            curLayUILayer = layer.open({
                type: 1,
                title: "查询窗口",
                area: ["390px", "300px"],
                shade: 0,
                offset: [
                    ($(window).height() * 0.1),
                    ($(window).width() * 0.05)
                ],
                maxmin: true,
                content: $("#queryBySearchLayer").html(),
                zIndex: layer.zIndex,
                success: null
            })
            form.render()
        })
    }

    /**
     * 点选查询
     */
    function bindSearchByPnt() {
        $("#searchByMouseClick").on("click", () => {
            removeOthers()
            let opts = $("#layerOptions")
            generateLayuiLayerFormOptions(opts)
            form.on("select(layerLayerOption)", function (data) {
                _layuiLayerNumber = data.value
            })
            useLayer(layer => {
                if (curLayUILayer !== null) {
                    layer.close(curLayUILayer)
                }
                curLayUILayer = layer.open({
                    type: 1,
                    title: "查询窗口",
                    area: ["390px", "300px"],
                    shade: 0,
                    skin: "myskin",
                    offset: [
                        ($(window).height() * 0.1),
                        ($(window).width() * 0.05)
                    ],
                    maxmin: true,
                    content: $("#queryByClickLayer").html(),
                    zIndex: layer.zIndex
                })
                form.render()
            })
            form.render()
            queryVectorLayerBy(Zondy.Enum.FeatureType.Pnt)
        })
    }

    /**
     * 拉框查询
     */
    function bindSearchByRegion() {
        $("#searchByRegion").on("click", () => {
            removeOthers()
            let opts = $("#layerOptions")
            generateLayuiLayerFormOptions(opts)
            form.on("select(layerLayerOption)", function (data) {
                _layuiLayerNumber = data.value
            })
            useLayer(layer => {
                if (curLayUILayer !== null) {
                    layer.close(curLayUILayer)
                }
                curLayUILayer = layer.open({
                    type: 1,
                    title: "查询窗口",
                    area: ["390px", "300px"],
                    shade: 0,
                    skin: "myskin",
                    offset: [
                        ($(window).height() * 0.1),
                        ($(window).width() * 0.05)
                    ],
                    maxmin: true,
                    content: $("#queryByClickLayer").html(),
                    zIndex: layer.zIndex
                })
                form.render()
            })
            form.render()
            queryVectorLayerBy(Zondy.Enum.FeatureType.Reg)
        })
    }

    bindCommonSearch()
    bindSearchByPnt()
    bindSearchByRegion()
}

function renderFormForLayuiLayer(form, layer) {
    form.on("submit(formDemo)",
        /**
         * @type {{field:InputClass}} data
         * @returns {boolean} 返回 false 则表示窗口不消失
         */
        function (data) {
            queryMapLayLoadingLayer = searchLoadingMsg(layer)
            queryService(resultLayers, data.field.inputLayer, data.field.inputName, (ss) => {
                querySuccess(ss)
            })
            return false
        })
}

function bindUseLayUILayerSearch(layer, form) {
    let opts = $("#options")
    generateLayuiLayerFormOptions(opts)
    renderFormForLayuiLayer(form, layer)
    bindSearchMenu(layer, form)
}

/**
 * 【测量】菜单
 */
function bindMeasuresMenu() {
// 【测量|距离】
    $("#measureLength").on("click", () => {
        removeOthers()
        interOp(Zondy.Enum.FeatureType.Lin)
    })

    // 【测量|面积】
    $("#measureArea").on("click", () => {
        removeOthers()
        interOp(Zondy.Enum.FeatureType.Reg)
    })
}

/**
 * 【地图】菜单
 */
function bindMapNavItemMenu() {
    $("#mapNavItem").on("click", () => {
        removeOthers()
    })
    editMenuModify.init()
    editMenuModify.disable()
}

/**
 * 右上【用户】菜单
 */
function bindUserMenu() {
    $("#quit").on("click", () => {
        window.location = 'login.html'
    })
}

function searchLoadingMsg(layer) {
    return layer.msg("查询中, 请稍候……", {
        icon: 16, shade: 0.01, time: 10 * 1000
    })
}

function useLayer(cb) {
    layui.use("layer", () => {
        let layer = layui.layer
        cb(layer)
    })
}